-- This file is part of the Fantasy Grounds Open Foundation Ruleset project. 
-- For the latest information, see http://www.fantasygrounds.com/
--
-- Copyright 2008 SmiteWorks Ltd.
--
-- This file is provided under the Open Game License version 1.0a
-- Refer to the license.html file for the full license text
--
-- All producers of work derived from this material are advised to
-- familiarize themselves with the license, and to take special
-- care in providing the definition of Product Identity (as specified
-- by the OGL) in their products.
--
-- All material submitted to the Open Foundation Ruleset project must
-- contain this notice in a manner applicable to the source file type.


function onInit()
	registerMenuItem("Create Effect", "insert", 5);

	if #getWindows() == 0 then
		createWindow();
	end
end

function onListRearranged()
	if #getWindows() == 0 then
		createWindow();
	end
end

function onSortCompare(w1, w2)
	if w1.label.getValue() == "" then return true; end
	if w2.label.getValue() == "" then return false; end
	return string.upper(w1.label.getValue()) > string.upper(w2.label.getValue());
end

function onMenuSelection(selection)
	createWindow();
end

function onDrop(x, y, draginfo)
	if draginfo.isType("number") then
		local w = createWindow();
		w.label.setValue(draginfo.getDescription());
		w.duration.setValue(draginfo.getNumberData());
		return true;
	end
end

function progressEffects(source)
	for k, v in ipairs(getWindows()) do
		if (not v.caster.getSource() and not source) or (source and v.caster.getSource() == source.getDatabaseNode()) then
			local oldvalue = v.duration.getValue();
			local newvalue = oldvalue + v.adjustment.getValue()
			v.duration.setValue(newvalue);
			
			if newvalue == 0 and newvalue ~= oldvalue then
				local msg = {};
				msg.text = "'" .. v.label.getValue() .. "' on " .. window.name.getValue() .. " expired";
				msg.font = "systemfont";
				msg.icon = "indicator_effect";
				
				ChatManager.addMessage(msg);
				
				v.close();
			end
		end
	end
end
